const baseURL = 'http://localhost:8088';

const USE_MOCK = false;

const request = (options) => {
    if (USE_MOCK) {
        return handleMockResponse(options);
    }
    return new Promise((resolve, reject) => {
        const token = uni.getStorageSync('token');
        const url = options.url.startsWith('/api') ? options.url : '/api' + options.url;
        
        uni.request({
            url: baseURL + url,
            method: options.method || 'GET',
            data: options.data || {},
            header: {
                'Authorization': token ? `Bearer ${token}` : '',
                ...options.header,
                'Content-Type': 'application/json',
            },
            timeout: 30000,
            success: (res) => {
                if (res.statusCode === 200) {
                    if (res.data.code === 200) {
                        resolve(res.data);
                    } else {
                        uni.showToast({
                            title: res.data.msg || '请求失败',
                            icon: 'none',
                            duration: 2000
                        });
                        reject(res.data);
                    }
                } else if (res.statusCode === 401) {
                    if (url.includes('/login') || url.includes('/register')) {
                        reject(res.data);
                    } else {
                        uni.removeStorageSync('token');
                        uni.removeStorageSync('userInfo');
                        uni.reLaunch({
                            url: '/pages/login/login'
                        });
                        reject(res);
                    }
                } else {
                    uni.showToast({
                        title: res.data?.msg || '请求失败',
                        icon: 'none',
                        duration: 2000
                    });
                    reject(res);
                }
            },
            fail: (err) => {
                console.error(`请求失败: ${baseURL}${url}`, err);
                let errorMsg = '网络请求失败';
                if (err.errMsg.includes('timeout')) {
                    errorMsg = '请求超时，请检查网络连接';
                } else if (err.errMsg.includes('ERR_NETWORK_CHANGED')) {
                    errorMsg = '网络连接不稳定，请重试';
                }
                uni.showToast({
                    title: errorMsg,
                    icon: 'none',
                    duration: 2000
                });
                reject(err);
            }
        });
    });
};

function handleMockResponse(options) {
    return new Promise((resolve) => {
        setTimeout(() => {
            if (options.url === '/user/login') {
                resolve({
                    code: 200,
                    msg: '登录成功',
                    data: {
                        id: '1001',
                        nickname: '测试用户',
                        avatarUrl: '../../static/images/avatar.png',
                        gender: 0,
                        token: 'mock_token_' + Date.now()
                    }
                });
            } else {
                resolve({
                    code: 200,
                    msg: '操作成功',
                    data: {}
                });
            }
        }, 500);
    });
}

export default {
    get(url, options = {}) {
        if (options.params) {
            const queryParams = {};
            for (const key in options.params) {
                const value = options.params[key];
                if (value !== undefined && value !== null) {
                    queryParams[key] = String(value);
                }
            }
            
            const queryString = Object.entries(queryParams)
                .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
                .join('&');
            
            if (queryString) {
                url += (url.includes('?') ? '&' : '?') + queryString;
            }
        }
        
        return request({
            url, 
            method: 'GET', 
            data: options.data || {}, 
            header: options.header || {}
        });
    },
    post(url, data = {}, options = {}) {
        if (options.params) {
            const queryParams = {};
            for (const key in options.params) {
                const value = options.params[key];
                if (value !== undefined && value !== null) {
                    queryParams[key] = String(value);
                }
            }
            
            const queryString = Object.entries(queryParams)
                .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
                .join('&');
            
            if (queryString) {
                url += (url.includes('?') ? '&' : '?') + queryString;
            }
        }
        
        return request({
            url, 
            method: 'POST', 
            data, 
            header: options.header || {}
        });
    },
    put(url, data = {}, options = {}) {
        if (options.params) {
            const queryParams = {};
            for (const key in options.params) {
                const value = options.params[key];
                if (value !== undefined && value !== null) {
                    queryParams[key] = String(value);
                }
            }
            
            const queryString = Object.entries(queryParams)
                .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
                .join('&');
            
            if (queryString) {
                url += (url.includes('?') ? '&' : '?') + queryString;
            }
        }
        
        return request({url, method: 'PUT', data, header: options.header || {}});
    },
    delete(url, data = {}, options = {}) {
        if (options.params) {
            const queryParams = {};
            for (const key in options.params) {
                const value = options.params[key];
                if (value !== undefined && value !== null) {
                    queryParams[key] = String(value);
                }
            }
            
            const queryString = Object.entries(queryParams)
                .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
                .join('&');
            
            if (queryString) {
                url += (url.includes('?') ? '&' : '?') + queryString;
            }
        }
        
        return request({url, method: 'DELETE', data, header: options.header || {}});
    }
};
